package com.delivery.www.servlet;

import com.alibaba.fastjson.JSON;
import com.delivery.www.po.Dish;
import com.delivery.www.po.Thumb;
import com.delivery.www.po.User;
import com.delivery.www.constant.Constants;
import com.delivery.www.service.ServiceImpl.DishServiceImpl;
import com.delivery.www.service.ServiceImpl.ThumbServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * @author 12970
 */
public class ThumbServlet extends BaseServlet {
    ThumbServiceImpl thumbService = new ThumbServiceImpl();
    DishServiceImpl dishService = new DishServiceImpl();

    /**
     * 点赞
     *
     * @param req  请求
     * @param resp 响应
     * @throws IOException 异常
     */
    public void doThumb(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        PrintWriter writer = resp.getWriter();
        User user = (User) req.getSession().getAttribute(Constants.USER_SESSION);
        if (user == null) {
            writer.print("login");
        } else {
            int dishId = Integer.parseInt(req.getParameter("dishId"));
            Thumb thumb = thumbService.getOneThumb(user.getUserId(), dishId);
            if (thumb != null) {
                writer.print("exist");
            } else {
                boolean b = thumbService.doThumb(user.getUserId(), dishId);
                if (b) {
                    writer.print("ok");
                } else {
                    writer.print("error");
                }
            }
        }
    }

    /**
     * 获取点赞
     *
     * @param req  请求
     * @param resp 响应
     * @throws IOException 异常
     */
    public void selectThumb(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        boolean flag = false;
        User user = (User) req.getSession().getAttribute(Constants.USER_SESSION);
        List<Thumb> thumbs = thumbService.getThumb(user.getUserId());
        List<Dish> dishes = dishService.getThumbDish(thumbs);
        req.setAttribute("flag", flag);
        req.setAttribute("dishes", dishes);
        req.getRequestDispatcher("/User/Thumb.jsp").forward(req, resp);
    }

    /**
     * 取消点赞
     *
     * @param req  请求
     * @param resp 响应
     * @throws IOException 异常
     */
    public void cancelThumb(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        PrintWriter writer = resp.getWriter();
        User user = (User) req.getSession().getAttribute(Constants.USER_SESSION);
        int dishId = Integer.parseInt(req.getParameter("dishId"));
        boolean b = thumbService.cancelThumb(user.getUserId(), dishId);
        if (b) {
            writer.print("ok");
        } else {
            writer.print("error");
        }
    }
}
